var currentType = 0; // 保存当前的客户类型
var currentOrderBy = 0; // 保存当前的类型
var currentReverse = 1; // 保存当前的排序


function getAll(type) {
    currentType = type;
    fetchData();
}

function filterData(orderByType) {
    currentOrderBy = orderByType;
    fetchData();
}

function reverse(isReverse) {
    currentReverse = isReverse;
    fetchData();
}

function fetchData() {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://testcalc.meiguanjia.net:8039/queryCustomer', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                // 解析响应数据
                var responseData = JSON.parse(xhr.responseText);
                renderData(responseData);
            } else {
                alert('请求失败，状态码：' + xhr.status);
            }
        }
    };
    xhr.timeout = 2000;
    xhr.ontimeout = function () {
        console.error('Request timed out');
    };
    xhr.onerror = function () {
        console.error('Network error occurred');
    };
    var jsonData = JSON.stringify({
        "type": currentType,
        "orderByType": currentOrderBy,
        "isReverse": currentReverse,
        "pageSize": 10,
        "pageNumber": 0
    });
    xhr.send(jsonData);
}

// 渲染数据的函数示例
function renderData(data) {
    // 假设 data 是一个包含客户信息的数组
    var container = document.getElementById('data-container');
    container.innerHTML = '';  // 清空容器

    for(var i = 0; i < data.content.length; i++){
        var eleData = data.content[i]

        // 根据名称长度选择字体大小
        var fontSize = eleData.name.length > 11 ? '9px' : 'initial';

        // 根据性别选择图片
        var imageSrc = eleData.sex === 'F' ? 'static/woman.jpg' : 'static/man.webp';


        var element= `
        <div class="contact premium" data-highquility = "${eleData.isHighQuality}" data-static = "${eleData.isStatic}" data-visit-time="${eleData.lastconsumetime}" data-unit-price="${eleData.req}" data-visit-frequency="${eleData.consumeFreq}" data-total-consumption="${eleData.consumeTotal}" data-recent-added="${eleData.recentAdded}">
            <img src="${eleData.avator}" alt="" class="avatarimg" onclick="showUserDetails('${encodeURIComponent(JSON.stringify(eleData))}')">
            <div class="info">
                <h2 style="font-size: ${fontSize};">${eleData.name}<img src="${imageSrc}" alt="" class="small-icon"></h2>
                <div class="details">
                    <p>电话: ${eleData.mobile}</p>
                    <p class="extra-info"><img src="static/contactman.jpg" alt="" class="small-icon1">${eleData.contactPerson}</p>
                </div>
            </div>
            <div class="last-message">
                <img src="static/phone.jpg" alt="电话图像" class="phone-icon" data-phone="${eleData.mobile}" onclick="showModal(this)">
                <p>上次消费：${eleData.registDate}</p>
            </div>
        </div>`;
        container.innerHTML += element
    }
}

// 显示模态框函数
function showModal(element) {
    var phoneNumber = element.getAttribute('data-phone');
    document.getElementById('phone-number').textContent = '电话号码: ' + phoneNumber;
    document.getElementById('modal').style.display = 'block';
}

// 关闭模态框
var modal = document.getElementById('modal');
var closeButton = document.getElementsByClassName('close')[0];
var cancelButton = document.getElementById('cancel-button');

closeButton.onclick = function() {
    modal.style.display = "none";
}

cancelButton.onclick = function() {
    modal.style.display = "none";
}

// 点击窗口外部关闭模态框
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}


// 显示用户详细信息的函数
function showUserDetails(data) {
    var userDetails = JSON.parse(decodeURIComponent(data));
    var detailsHTML = `
    <h2>姓名：${userDetails.name}</h2>
    <p>性别: ${userDetails.sex}</p>
    <p>电话: ${userDetails.mobile}</p>
    <p>生日: ${userDetails.birthDay}</p>
    <p>消费总额: ${userDetails.consumeTotal}</p>
    <p>来店时间: ${userDetails.lastconsumetime}</p>
    <p>来店频率: ${userDetails.consumeFreq}</p>
    `;
    document.getElementById('user-details').innerHTML = detailsHTML;
    document.getElementById('userModal').style.display = 'block';
}

// 关闭模态框
var userModal = document.getElementById('userModal');
var closeUserModal = document.getElementById('userModal').getElementsByClassName('close')[0];

closeUserModal.onclick = function() {
    userModal.style.display = "none";
}

window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
    if (event.target == userModal) {
        userModal.style.display = "none";
    }
}

function toggleArrow(arrowElement) {
    // 检查当前箭头的方向
    if (arrowElement.classList.contains('up')) {
        // 如果当前是向上，切换为向下
        arrowElement.classList.remove('up');
        reverse(1);  // 假设这个方向是向下
    } else {
        // 如果当前是向下，切换为向上
        arrowElement.classList.add('up');
        reverse(0);  // 假设这个方向是向上
    }
}

// 初始化时加载全部客户数据
getAll(0);
